﻿using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using Gumini.JulaDB.Engine;

namespace Gumini.JulaDB
{
    /// <summary>
    /// Encapsulates the results of executing a database command.
    /// </summary>
    public class CommandResult
    {
        internal static CommandResult CreateSuccess(LogMessage message, int rowsAffected, RecordSet resultTable = null)
        {
            return new CommandResult(true, rowsAffected, resultTable, new[] { message });
        }

        internal static CommandResult CreateFailure(IEnumerable<LogMessage> messages)
        {
            return new CommandResult(false, 0, null, messages);
        }

        internal static CommandResult CreateFailure(LogMessage message)
        {
            return new CommandResult(false, 0, null, new[] { message });
        }

        private CommandResult(bool isSuccessful, int rowsAffected, RecordSet resultTable, IEnumerable<LogMessage> messages)
        {
            this.IsSuccessful = isSuccessful;
            this.NumberOfRowsAffected = rowsAffected;
            this.Messages = new ReadOnlyCollection<LogMessage>(messages.ToList());
            this.RecordSet = resultTable;
        }

        /// <summary>
        /// True if the query was executed successfully.
        /// </summary>
        public bool IsSuccessful { get; private set; }

        public ReadOnlyCollection<LogMessage> Messages { get; private set; }

        public RecordSet RecordSet { get; private set; }

        public int NumberOfRowsAffected { get; private set; }

        public override string ToString()
        {
            return String.Format("succesful: {0}, messages: {1}, has record set: {2}", IsSuccessful, Messages.Count, RecordSet != null);
        }
    }
}
